<template>
  <view class="app-container">
    <view class="title-padding"></view>
    <scroll-view scroll-y="true" class="scroll-v">
      <view>
        <view class="mode-container flex flex-wrap align-stretch">
          <view class="top-view">
            <view class="tool-row flex justify-between align-center">
              <view class="flex align-center justify-between tool-left">
                <view class="picker-prefix-name">一胆</view>
                <!-- <picker
                  @change="onMaNameChange"
                  :value="maIndex"
                  :range="totals"
                  range-key="name"
                >
                  <view class="picker-prefix-name">
                    {{ totals[maIndex] ? totals[maIndex].name : '胆码' }}
                  </view>
                  <view class="picker-suffix-icon">
                    <image mode="widthFix" src="../../static/form/choose.png" />
                  </view>
                </picker> -->
              </view>
              <view class="tool-right text-white" @click="handleSelectAllTop">
                全
              </view>
            </view>
            <view class="number-row grid col-6">
              <view
                @click="danBoxChange(idx + 1)"
                class="number-item"
                :class="numbers.indexOf(idx + 1) > -1 ? 'active' : ''"
                v-for="(item, idx) in 11"
                :key="idx + 1"
              >
                {{ idx + 1 }}
              </view>
            </view>
          </view>
          <view class="bottom-view">
            <view class="tool-row flex justify-between align-center">
              <view class="tool-left">开出个数</view>
              <view class="tool-right text-white" @click="handleCleanUpTop">
                清
              </view>
            </view>
            <view class="check-row grid col-3">
              <view
                class="check-item flex align-center justify-center"
                v-for="(item, idx) in 6"
                :key="idx"
              >
                <view class="flex justify-center align-center">
                  <view class="input-item" @click="danCountChange(idx)">
                    <view class="check-icon" v-if="counts.indexOf(idx) > -1">
                      <image
                        mode="widthFix"
                        src="../../static/card/selected.png"
                      />
                    </view>
                    <view class="check-icon" v-if="counts.indexOf(idx) === -1">
                      <image
                        mode="widthFix"
                        src="../../static/card/unselected.png"
                      />
                    </view>
                  </view>
                  <view
                    class="count-item"
                    :class="counts.indexOf(idx) > -1 ? 'active' : ''"
                  >
                    {{ idx }}个
                  </view>
                </view>
              </view>
            </view>
            <view class="mynumber-row flex justify-between">
              <button
                class="cu-btn left-button bg-blue"
                @tap="handleGoToMyNumbers"
              >
                我的组号
                <view class="cu-tag badge">
                  <block>{{ myNumbersNumebr }}</block>
                </view>
              </button>
              <button class="cu-btn save-button" @tap="handleSaveMyNumbers">
                添加
              </button>
            </view>
          </view>
        </view>

        <view class="quate-container flex flex-wrap align-stretch">
          <view class="quate-view">
            <view class="tool-row flex justify-between align-center">
              <view class="tool-left">选择指标</view>
              <view class="tool-right">
                <button
                  class="cu-btn left-button"
                  @click="handleOpenFilterModal"
                >
                  过滤条件
                  <view class="cu-tag badge">
                    <block>{{ filterBadgeNumber }}</block>
                  </view>
                </button>
              </view>
            </view>
            <view class="check-row grid col-4">
              <view
                class="check-item"
                v-for="(item, index) in quateData"
                :key="index"
              >
                <view
                  @click="showQuateConfigModal(item.key, item.name, item.data)"
                  class="check-button"
                  :class="item.data.length > 0 ? 'checked' : ''"
                >
                  {{ item.name }}
                  <view class="cu-tag badge" v-if="item.data.length > 0">
                    <block>{{ item.data.length }}</block>
                  </view>
                </view>
                <view
                  class="cu-modal quate-config-modal"
                  :class="modalVisible[item.key] ? 'show' : ''"
                >
                  <quate-count-modal
                    v-if="item.type === 'count' && modalVisible[item.key]"
                    :maxCount="item.key === 'lian' ? 5 : 6"
                    :title="curQuateTitle"
                    :data="curQuateData"
                    @hide="hideQuateConfigModal(item.key)"
                    @confirm="confirmQuateConfigModal(item.key, index, $event)"
                  ></quate-count-modal>
                  <quate-chong-modal
                    v-if="
                      item.type === 'duplicateNumbers' && modalVisible[item.key]
                    "
                    :maxCount="6"
                    :region="regionList[regionIndex].name"
                    :title="curQuateTitle"
                    :data="curQuateData"
                    @hide="hideQuateConfigModal(item.key)"
                    @confirm="confirmQuateConfigModal(item.key, index, $event)"
                  ></quate-chong-modal>
                  <quate-bili-modal
                    v-if="item.type === 'bili' && modalVisible[item.key]"
                    :title="curQuateTitle"
                    :data="curQuateData"
                    @hide="hideQuateConfigModal(item.key)"
                    @confirm="confirmQuateConfigModal(item.key, index, $event)"
                  ></quate-bili-modal>
                  <quate-kuadu-modal
                    v-if="item.type === 'kuadu' && modalVisible[item.key]"
                    :title="curQuateTitle"
                    :data="curQuateData"
                    @hide="hideQuateConfigModal(item.key)"
                    @confirm="confirmQuateConfigModal(item.key, index, $event)"
                  ></quate-kuadu-modal>
                </view>
              </view>
            </view>
            <view class="bottom-row flex justify-between">
              <view class="label">
                重号地区：{{
                  regionList.length > 0 && regionList[regionIndex].name
                }}
              </view>
              <picker
                @change="onRegionChange"
                :value="regionIndex"
                :range="regionList"
                range-key="name"
              >
                <view class="arrow">
                  <image mode="widthFix" src="../../static/card/arrow.png" />
                </view>
              </picker>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    <view class="filter-container fixed flex align-center justify-between">
      <view class="left-area"></view>
      <view class="right-area">
        <button class="cu-btn generate-button" @tap="handleGenerate">
          生成组号
        </button>
      </view>
      <view
        class="cu-modal filter-modal"
        :class="filterModalVisible ? 'show' : ''"
      >
        <filter-modal
          title="过滤条件"
          v-if="filterModalVisible"
          :filters="filterData"
          @update="handleUpdateQuateModal"
          @remove="handleRemoveQuateData"
          @hide="handleCloseFilterModal"
        ></filter-modal>
      </view>
    </view>
  </view>
</template>

<script>
import QuateCountModal from '@/components/quateConfigModal/countModal.vue'
import QuateBiliModal from '@/components/quateConfigModal/biliModal.vue'
import QuateKuaduModal from '@/components/quateConfigModal/kuaduModal.vue'
import QuateChongModal from '@/components/quateConfigModal/chongModal.vue'
import FilterModal from '@/components/filterModal/modal.vue'
import { generateZuhao2 } from '@/api/number'
import { quateDataConst } from '@/consts/index'
import { getCaipiaoCategoryList } from '@/api/common'

const getUnitByKeyName = key => {
  switch (key) {
    case 'odd':
      return '个'
    case 'big':
      return '个'
    case 'prime':
      return '个'
    case 'lian':
      return '个'
    case 'duplicateNumbers':
      return '个'
    case 'jioubi':
      return ''
    case 'daxiaobi':
      return ''
    case 'zhihebi':
      return ''
  }
}

export default {
  components: {
    QuateCountModal,
    QuateBiliModal,
    QuateKuaduModal,
    QuateChongModal,
    FilterModal,
  },
  computed: {},
  data() {
    return {
      totals: [
        {
          value: 'dan1',
          name: '一码',
        },
        {
          value: 'dan2',
          name: '二码',
        },
        {
          value: 'dan3',
          name: '三码',
        },
        {
          value: 'dan4',
          name: '四码',
        },
        {
          value: 'dan5',
          name: '五码',
        },
      ],
      maIndex: 0,
      numbers: [],
      counts: [],
      curQuateData: [],
      curQuateTitle: '',
      quateData: JSON.parse(JSON.stringify(quateDataConst)),
      filterData: [],
      modalVisible: {},
      filterModalVisible: false,
      filterModalVisibleFlag: false,
      filterBadgeNumber: 0,
      myNumbersNumebr: 0,
      regionList: [],
      regionIndex: 0,
      caipiao_id: null,
    }
  },
  watch: {
    quateData: {
      // TODO fix ? why oldval === val and calculate wrong ?
      // TODO fix ? why after remove first modal data shows wrong ? cache ?
      handler: function (val, oldVal) {
        // console.log(val, oldVal)
        this.filterData = val.filter(e => {
          return e.data.length > 0
        })

        this.filterBadgeNumber = val.filter(e => {
          return e.data.length > 0
        }).length
      },
      deep: false,
    },
  },
  created() {
    this.quateData.forEach(item => {
      this.$set(this.modalVisible, item.key, false)
    })
    this.getCateList()
  },
  onLoad(e) {},
  onHide() {
    uni.setStorageSync('from', '')
  },
  onShow() {
    let numbers = uni.getStorageSync('numbers')
      ? JSON.parse(uni.getStorageSync('numbers'))
      : []
    let numbersIndex = uni.getStorageSync('numbersIndex')
      ? Number(uni.getStorageSync('numbersIndex'))
      : 0
    let chartNumbers = uni.getStorageSync('chartNumbers')
      ? JSON.parse(uni.getStorageSync('chartNumbers'))
      : []
    let fromPage = uni.getStorageSync('from')
      ? uni.getStorageSync('from')
      : undefined

    this.myNumbersNumebr = numbers.length
    let curNumber = undefined

    if (fromPage === 'chart') {
      this.numbers = chartNumbers
    } else if (fromPage === 'mine') {
      let curNumber = numbers[numbersIndex]
    }

    console.log(`- curNumber: `, curNumber)
    if (!curNumber) return
    this.numbers = curNumber.numbers
    this.counts = curNumber.counts
    let newQuateData = JSON.parse(JSON.stringify(quateDataConst))
    curNumber.rules.forEach(rule => {
      let index = this.quateData.findIndex(q => q.key === rule.key)
      if (index > -1) {
        newQuateData[index].data = rule.data
      }
    })
    this.quateData = newQuateData
  },
  methods: {
    getCateList() {
      getCaipiaoCategoryList().then(res => {
        if (res.code === 1 && res.data) {
          let resList = []
          resList = res.data.map(data => {
            return {
              id: data.c_id,
              name: data.c_name,
            }
          })
          this.regionList = resList
          this.caipiao_id = resList[0].id
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none',
          })
        }
      })
    },
    onRegionChange(e) {
      this.regionIndex = e.detail.value
      this.caipiao_id = this.regionList[this.regionIndex].id
    },
    onMaNameChange(e) {
      this.maIndex = e.detail.value
    },
    danBoxChange(number) {
      let index = this.numbers.indexOf(number)

      if (index > -1) {
        this.numbers.splice(index, 1)
      } else {
        this.numbers.push(number)
      }
    },
    danCountChange(count) {
      let index = this.counts.indexOf(count)
      if (index > -1) {
        this.counts.splice(index, 1)
      } else {
        this.counts.push(count)
      }
    },
    handleSelectAllTop() {
      this.numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
    },
    handleCleanUpTop() {
      this.numbers = []
      this.counts = []
    },
    showQuateConfigModal(key, title, data) {
      this.curQuateTitle = title
      this.curQuateData = data
      this.modalVisible[key] = true
    },
    hideQuateConfigModal(key) {
      this.modalVisible[key] = false
      if (this.filterModalVisibleFlag) {
        this.handleOpenFilterModal()
      }
      this.curQuateTitle = ''
      this.curQuateData = []
    },
    confirmQuateConfigModal(key, index, data) {
      this.modalVisible[key] = false
      if (this.filterModalVisibleFlag) {
        this.handleOpenFilterModal()
      }
      this.curQuateTitle = ''
      this.curQuateData = []
      this.$set(this.quateData, index, { ...this.quateData[index], data })
    },
    handleOpenFilterModal() {
      this.filterModalVisible = true
      this.filterModalVisibleFlag = true
    },
    handleCloseFilterModal() {
      this.filterModalVisible = false
      this.filterModalVisibleFlag = false
    },
    handleUpdateQuateModal(name, data) {
      this.filterModalVisible = false
      this.curQuateTitle = name
      this.curQuateData = data
      switch (name) {
        case '大数':
          this.modalVisible.big = true
          break
        case '奇数':
          this.modalVisible.odd = true
          break
        case '质数':
          this.modalVisible.prime = true
          break
        case '连号':
          this.modalVisible.lian = true
          break
        case '奇偶比':
          this.modalVisible.jioubi = true
          break
        case '大小比':
          this.modalVisible.daxiaobi = true
          break
        case '质合比':
          this.modalVisible.zhihebi = true
          break
        case '跨度':
          this.modalVisible.kuadu = true
          break
      }
    },
    handleRemoveQuateData(name) {
      let index = this.quateData.findIndex(row => row.name === name)
      if (index > -1) {
        this.$set(this.quateData, index, { ...this.quateData[index], data: [] })
      }
      this.curQuateData = []
      this.curQuateTitle = ''
    },
    handleGoToMyNumbers() {
      uni.navigateTo({
        url: '/pages/number/myNumbers',
      })
    },
    handleSaveMyNumbers() {
      let numbers = uni.getStorageSync('numbers')
        ? JSON.parse(uni.getStorageSync('numbers'))
        : []

      let number = {}
      number.index = numbers.length
      number.numbers = this.numbers
      number.counts = this.counts

      let commonRules = this.quateData
        .filter(data => data.data.length > 0)
        .map(data => {
          return {
            key: data.key,
            name: data.name,
            data: data.data,
            value: data.data.map(e => e + getUnitByKeyName(data.key)).join(','),
            unit: getUnitByKeyName(data.key),
          }
        })
      if (number.numbers.length > 0) {
        numbers.push(number)
        numbers = numbers.map(n => {
          return { ...n, rules: commonRules }
        })
        this.myNumbersNumebr = numbers.length
        uni.setStorage({
          key: 'numbers',
          data: JSON.stringify(numbers),
          success: () => {
            uni.showToast({
              title: '添加成功!',
              icon: 'none',
            })
          },
        })
      } else {
        uni.showToast({
          title: '请选号码!',
          icon: 'none',
        })
      }
    },
    handleGenerate() {
      let maKey = this.totals[this.maIndex].value
      let cxKey = maKey + 'cx'
      let numbersData = uni.getStorageSync('numbers')
        ? JSON.parse(uni.getStorageSync('numbers'))
        : []

      if (numbersData.length === 0) {
        uni.showToast({
          title: '请先添加到我的组号!',
          icon: 'none',
        })
        return
      }

      let danList = JSON.stringify(
        numbersData.map(d => {
          return {
            dan: d.numbers.length > 0 ? d.numbers.join(',') : '',
            chu: d.counts.length > 0 ? d.counts.join(',') : '',
          }
        })
      )

      let data = {
        danList,
        caipiao_id:
          this.quateData[7].data.length > 0 ? this.caipiao_id : undefined,
      }

      this.quateData.forEach(row => {
        if (row.data.length > 0) {
          data[row.key] = row.data.join(',')
        }
      })

      generateZuhao2(data).then(res => {
        if (res.code === 1 && res.data) {
          this.numbers = []
          this.counts = []
          this.quateData = JSON.parse(JSON.stringify(quateDataConst))
          this.filterBadgeNumber = 0
          this.myNumbersNumebr = 0

          uni.setStorageSync('generatedParams', JSON.stringify(data))
          uni.setStorageSync('numbers', undefined)
          uni.setStorageSync('numbersIndex', undefined)
          uni.setStorageSync('chartNumbers', undefined)

          uni.setStorage({
            key: 'generated',
            data: res.data,
            success: () => {
              uni.navigateTo({
                url: '/pages/number/generated',
              })
            },
          })
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.app-container {
  width: 100%;
  // height: 100vh;
  background-color: #ffffff;
  position: relative;
  .scroll-v {
    width: 100%;
    height: calc(100vh - 88upx);
    /* #ifdef H5 */
    height: calc(100vh - var(--window-bottom) - var(--window-top) - 88upx);
    /* #endif */
    flex: 1;
    .mode-container {
      margin: 0 28upx 20upx;
      padding-top: 20upx;
      height: 814upx;
      box-shadow: 0px 2px 6px 0px rgba(12, 124, 202, 0.1);
      border-radius: 20upx;
      .top-view {
        width: 100%;
        height: 352upx;
        background-color: #ffffff;
        border-radius: 20upx 20upx 0 0;
        padding: 22upx 20upx;
        .tool-row {
          height: 76upx;
          padding-bottom: 16upx;
          border-bottom: 1px solid #edf2f6;
          .tool-left {
            cursor: pointer;
            font-size: 32upx;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #333333;
            line-height: 44upx;
          }
          .tool-right {
            width: 60upx;
            height: 60upx;
            background: #149eff;
            border-radius: 20upx;
            text-align: center;
            font-size: 36upx;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            line-height: 60upx;
            cursor: pointer;
          }

          .picker-prefix-name {
            display: inline-block;
            vertical-align: top;
          }
          .picker-suffix-icon {
            display: inline-block;
            height: 44upx;
            margin-left: 22upx;
            uni-image {
              width: 22upx;
              height: 28upx;
            }
          }
        }
        .number-row {
          height: 250upx;
          width: 100%;
          padding: 40upx 20upx;
          .number-item {
            width: 80upx;
            height: 80upx;
            display: inline-block;
            margin-right: 26.4upx;
            line-height: 80upx;
            border-radius: 40upx;
            background-color: #edf2f6;
            color: #71808a;
            text-align: center;
            font-size: 36upx;
            &:nth-child(6n + 6) {
              margin-right: 0;
            }
            &.active {
              background-color: #da2626;
              color: #ffffff;
            }
          }
        }
      }

      .bottom-view {
        width: 100%;
        height: 434upx;
        background-color: #ffffff;
        border-radius: 0 0 20upx 20upx;
        padding: 22upx 20upx;
        .tool-row {
          height: 76upx;
          padding-bottom: 16upx;
          border-bottom: 1px solid #edf2f6;

          .tool-left {
            font-size: 32upx;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #333333;
            line-height: 44upx;
          }
          .tool-right {
            width: 60upx;
            height: 60upx;
            background: #149eff;
            border-radius: 20upx;
            text-align: center;
            font-size: 36upx;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            line-height: 60upx;
            cursor: pointer;
          }
        }
        .check-row {
          height: 222upx;
          padding: 32upx 0upx;
          border-bottom: 1px solid #edf2f6;
          .check-item {
            .input-item {
              display: inline-block;
              width: 60upx;
              height: 60upx;
              line-height: 60upx;
              border-radius: 30upx;
              margin-right: 16upx;
              vertical-align: top;
              text-align: center;
              .check-icon {
                width: 60upx;
                height: 60upx;
              }
            }
            .count-item {
              display: inline-block;
              vertical-align: top;
              line-height: 60upx;
              color: #71808a;
              &.active {
                color: #da2626;
              }
            }
          }
        }
        .mynumber-row {
          padding: 32upx 0 0 0;
          .cu-btn {
            width: 180upx;
            height: 60upx;
            font-size: 28upx;
            text-align: center;
            line-height: 60upx;
            border-radius: 30upx;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
          }

          .save-button {
            margin-right: 10upx;
            background-color: #edf2f6;
            color: #2999ff;
          }
        }
      }
    }
    .quate-container {
      margin: 20upx 28upx;
      height: 376upx;
      box-shadow: 0px 2px 6px 0px rgba(12, 124, 202, 0.1);
      border-radius: 20upx;
      background-color: #ffffff;

      .quate-view {
        width: 100%;
        border-radius: 20upx 20upx 0 0;
        padding: 22upx 20upx;
        .tool-row {
          height: 76upx;
          padding-bottom: 16upx;
          border-bottom: 1px solid #edf2f6;

          .tool-left {
            font-size: 32upx;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #333333;
            line-height: 44upx;
          }

          .tool-right {
            background: #149eff;
            border-radius: 60upx;
            text-align: center;
            font-size: 36upx;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            line-height: 60upx;
            cursor: pointer;

            .left-button {
              background-color: #2999ff;
              color: #ffffff;
              border-radius: 60upx;
            }
          }
        }
        .check-row {
          height: 200upx;
          padding: 32upx 24upx;
          border-bottom: 1px solid #edf2f6;
          .check-item {
            .check-button {
              position: relative;
              width: 120upx;
              height: 60upx;
              line-height: 60upx;
              font-size: 28upx;
              text-align: center;
              background-color: #edf2f6;
              border-radius: 30upx;
              color: #71808a;
              cursor: pointer;
              &.checked {
                background-color: #da2626;
                color: #ffffff;
              }
            }
          }
        }
        .bottom-row {
          height: 80upx;
          padding: 20upx 0;
          background-color: #ffffff;
          .label {
            font-size: 28upx;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #71808a;
            line-height: 40upx;
          }
          .arrow {
            display: inline-block;
            width: 20upx;
          }
        }
      }
    }
  }

  .filter-container {
    position: absolute;
    bottom: 0;
    height: 88upx;
    width: 100%;
    background-color: #ffffff;
    padding: 14upx 28upx;
    border-top: 1px solid #edeff6;
    .cu-btn {
      width: 180upx;
      height: 60upx;
      font-size: 28upx;
      text-align: center;
      line-height: 60upx;
      border-radius: 30upx;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
    }

    .save-button {
      margin-right: 10upx;
      background-color: #edf2f6;
      color: #2999ff;
    }

    .generate-button {
      background-color: #edf2f6;
      color: #2999ff;
    }
  }
}
</style>
